<script lang="ts">
	import MenuButton from '$components/business/menu-button';
	import Product from '$components/business/product/product.svelte';
	import { createEventDispatcher } from 'svelte';
	import Empty from '$lib/empty/itemEmpty.svg';
	import Select, { Option } from '@smui/select';
	import Icon from '@smui/select/icon';
	import { PageLoading } from '$components/basic/loading';
	import PagingNavigation from '$components/basic/page-navigation/PagingNavigation.svelte';

	let sortList = [
		{ icon: 'sort', label: 'Default' },
		{ icon: 'swap_vert', label: 'Date,old to new' },
		{ icon: 'swap_vert', label: 'Date,new to old' },
		{ icon: 'height', label: 'Price,low to high' },
		{ icon: 'height', label: 'Price,high to low' },
		{ icon: 'sort_by_alpha', label: 'Alphabetically,A-Z' },
		{ icon: 'sort_by_alpha', label: 'Alphabetically,Z-A' }
	];

	export let page;
	export let total;
	export let loading: boolean = true;
	export let error: string | number;
	export let list: Partial<Product.Detail>[] = [];
	export let sortValue = sortList[0].label;

	const dispatch = createEventDispatcher();

	function changeSort() {
		dispatch('queryData', { page, sort: sortList.findIndex((item) => item.label === sortValue) });
	}
	function queryData(event: CustomEvent) {
		dispatch('queryData', event.detail);
	}
</script>

<div class="h-full flex-1">
	{#if list.length}
		<div class="flex flex-row items-center justify-between pl-30px">
			<Select
				class="clear-select-underline w-300px"
				variant="filled"
				bind:value={sortValue}
				on:SMUISelect:change={changeSort}
			>
				<Icon class="material-icons" slot="leadingIcon">sort</Icon>
				{#each sortList as sort}
					<Option bind:value={sort.label}>
						{sort.label}
					</Option>
				{/each}
			</Select>
			<PagingNavigation
				position="end"
				bind:total
				bind:currentPage={page}
				on:pageNavigationChange={queryData}
			></PagingNavigation>
		</div>
	{/if}

	<PageLoading bind:loading bind:err_status={error}>
		{#if !list.length && !loading}
			<div class="w-full flex-cc">
				<img src={Empty} alt="no items" />
			</div>
		{/if}
		<div class="flex-1 grid grid-cols-4 gap-30px pl-30px">
			{#each list as _product}
				<Product
					style="animation: fade-in both;animation-timeline: view(); animation-range: contain 0% contain 10%"
					detail={_product}
				/>
			{/each}
		</div>
	</PageLoading>
	{#if list.length}
		<PagingNavigation
			position="end"
			variableSize
			bind:total
			bind:currentPage={page}
			on:pageNavigationChange={queryData}
		/>
	{/if}
</div>
